package com.ridbor001.demo.servlet;

import com.ridbor001.demo.bean.RDBAdmin;
import com.ridbor001.demo.bean.RDBStudent;
import com.ridbor001.demo.bean.RDBTeacher;
import com.ridbor001.demo.bean.RDBUser;
import com.ridbor001.demo.service.RDBAdminService;
import com.ridbor001.demo.service.RDBStudentService;
import com.ridbor001.demo.service.RDBTeacherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Optional;

@WebServlet("/login")
public class RDBLoginServlet extends HttpServlet {
    RDBStudentService rdbStudentService = new RDBStudentService();
    RDBTeacherService rdbTeacherService = new RDBTeacherService();
    RDBAdminService rdbAdminService = new RDBAdminService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("id");
        String password = request.getParameter("password");
        System.out.println(id+password);
        Optional<RDBUser> user = null;
        try {
            user = findUser(id, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        HttpSession session = request.getSession();
        if (user.isPresent()) {
            session.setAttribute("user", user.get());
            session.removeAttribute("errorMessage");
            response.sendRedirect("rDBDashboard.jsp");
        } else {
            session.setAttribute("errorMessage", "用户名或密码错误");
            response.sendRedirect("rDBLogin.jsp"); // 加上这行
        }
    }

    private Optional<RDBUser> findUser(String id, String password) throws SQLException {
        // 1. 尝试查找学生
        Optional<RDBStudent> student = rdbStudentService.findStudentByIdAndPassword(id, password);
        if (student.isPresent()) {
            return Optional.of(student.get());
        }

        // 2. 尝试查找教师
        Optional<RDBTeacher> teacher = rdbTeacherService.findTeacherByIdAndPassword(id, password);
        if (teacher.isPresent()) {
            return Optional.of(teacher.get());
        }
        // 3. 尝试查找管理员
        Optional<RDBAdmin> admin = rdbAdminService.findAdminByIdAndPassword(id, password);
        if (admin.isPresent()) {
            return Optional.of(admin.get());
        }
        return Optional.empty(); // 返回一个空Optional而不是null
    }
}